package com.agriculture.controller;

import com.agriculture.common.Response;
import com.agriculture.domain.User;
import com.agriculture.dto.PasswordChangeDTO;
import com.agriculture.dto.UserProfileDTO;
import com.agriculture.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/api/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/profile/{userId}")
    public ResponseEntity<?> getUserProfile(@PathVariable Long userId) {
        try {
            User user = userService.getUserProfile(userId);
            return ResponseEntity.ok(Response.success("获取成功", user));
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }

    @PutMapping("/profile/update/{userId}")
    public ResponseEntity<?> updateUserProfile(
            @PathVariable Long userId,
            @RequestBody UserProfileDTO profileDTO) {
        try {
            User user = userService.updateUserProfile(userId, profileDTO);
            return ResponseEntity.ok(Response.success("更新成功", user));
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }
    
    @PutMapping("/password/update/{userId}")
    public ResponseEntity<?> changePassword(
            @RequestAttribute Long userId,
            @RequestBody PasswordChangeDTO passwordDTO) {
        try {
            userService.changePassword(userId, passwordDTO);
            return ResponseEntity.ok(Response.success("密码修改成功", null));
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }
} 